<template>
  <div class="add-teacher-page">
    <div class="page-header">
      <h1>👨‍🏫 管理员添加教师</h1>
      <p class="subtitle">填写教师账号信息进行添加</p>
    </div>

    <div class="content-container">
      <div class="form-card">
        <form @submit.prevent="handleSubmit">
          <!-- 用户名 -->
          <div class="form-group">
            <label for="username">
              <span class="required">*</span> 用户名
            </label>
            <input 
              type="text" 
              id="username" 
              v-model="formData.username"
              placeholder="请输入用户名"
              required
            />
          </div>

          <!-- 账号 -->
          <div class="form-group">
            <label for="account">
              <span class="required">*</span> 账号
            </label>
            <input 
              type="text" 
              id="account" 
              v-model="formData.account"
              placeholder="请输入登录账号"
              required
            />
          </div>

          <!-- 密码 -->
          <div class="form-group">
            <label for="password">
              <span class="required">*</span> 密码
            </label>
            <input 
              type="password" 
              id="password" 
              v-model="formData.password"
              placeholder="请输入密码"
              required
            />
          </div>

          <!-- 身份 -->
          <div class="form-group">
            <label for="role">
              <span class="required">*</span> 身份
            </label>
            <select 
              id="role" 
              v-model="formData.role"
              required
            >
              <option value="" disabled>请选择身份</option>
              <option value="1">管理员</option>
              <option value="2">教师</option>
              <option value="3">学生</option>
              <option value="5">家长</option>
            </select>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <button type="button" class="btn btn-secondary" @click="handleReset">
              🔄 重置
            </button>
            <button type="submit" class="btn btn-primary" :disabled="isSubmitting">
              <span v-if="!isSubmitting">✅ 确认添加</span>
              <span v-else>⏳ 处理中...</span>
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 结果提示框 -->
    <div class="result-modal" v-if="showResult" @click="closeResult">
      <div class="result-content" @click.stop>
        <div class="result-header" :class="resultType">
          <span class="result-icon">{{ resultType === 'success' ? '✅' : '❌' }}</span>
          <h3>{{ resultType === 'success' ? '添加成功' : '添加失败' }}</h3>
        </div>
        <div class="result-body">
          <p>{{ resultMessage }}</p>
          <div v-if="resultDetails" class="result-details">
            <pre>{{ resultDetails }}</pre>
          </div>
        </div>
        <button class="btn btn-primary" @click="closeResult">确定</button>
      </div>
    </div>
  </div>
</template>

<script>
import logger from '../utils/logger.js'

export default {
  name: 'AddTeacher',
  data() {
    return {
      formData: {
        username: '',
        account: '',
        password: '',
        role: ''
      },
      isSubmitting: false,
      showResult: false,
      resultType: 'success',
      resultMessage: '',
      resultDetails: null
    }
  },
  methods: {
    // 重置表单
    handleReset() {
      const shouldReset = arguments.length > 0 ? arguments[0] : true;
      if (!shouldReset || confirm('确定要重置表单吗？')) {
        this.formData = {
          username: '',
          account: '',
          password: '',
          role: ''
        }
        logger.log('🔄 表单已重置')
      }
    },
    
    // 提交表单
    async handleSubmit() {
      // 验证表单数据
      if (!this.formData.username || !this.formData.account || !this.formData.password || !this.formData.role) {
        alert('❌ 请填写所有必填项')
        return
      }
      
      this.isSubmitting = true
      
      try {
        logger.log('📤 准备添加教师:', this.formData)
        logger.log('📋 原始role值（字符串）:', this.formData.role, '类型:', typeof this.formData.role)
        logger.log('🌐 [API] 调用添加用户接口')
        logger.log('🔗 [API] 接口地址: /goc/admin/addUser')
        
        // 导入axios实例
        const api = (await import('@/api/config.js')).default
        
        // 准备请求数据
        const requestData = {
          username: this.formData.username,
          account: this.formData.account,
          password: this.formData.password,
          role: parseInt(this.formData.role) // 将字符串转换为数字
        }
        
        logger.log('📊 请求数据:', requestData)
        logger.log('📋 转换后role值（数字）:', requestData.role, '类型:', typeof requestData.role)
        
        // 调用API
        const response = await api.post('/goc/admin/addUser', requestData, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        
        logger.log('✅ 添加成功:', response)
        
        // 成功
        this.showResultModal('success', `✅ 成功添加账号：${this.formData.username}`)
        
        // 重置表单（不需要确认）
        setTimeout(() => {
          this.formData = {
            username: '',
            account: '',
            password: '',
            role: ''
          }
          logger.log('🔄 表单已自动重置')
        }, 1500)
        
      } catch (error) {
        logger.error('❌ 添加失败:', error)
        logger.error('📊 错误详情:', {
          status: error.response?.status,
          statusText: error.response?.statusText,
          data: error.response?.data
        })
        
        const errorMsg = error.response?.data?.message || error.message || '未知错误'
        this.showResultModal('error', '❌ 添加失败，请重试', errorMsg)
      } finally {
        this.isSubmitting = false
      }
    },
    
    // 显示结果弹窗
    showResultModal(type, message, details = null) {
      this.resultType = type
      this.resultMessage = message
      this.resultDetails = details
      this.showResult = true
    },
    
    // 关闭结果弹窗
    closeResult() {
      this.showResult = false
      this.resultDetails = null
    }
  }
}
</script>

<style scoped>
.add-teacher-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px 20px;
}

.page-header {
  text-align: center;
  color: white;
  margin-bottom: 40px;
}

.page-header h1 {
  font-size: 36px;
  margin-bottom: 10px;
  font-weight: 700;
}

.subtitle {
  font-size: 16px;
  opacity: 0.9;
}

.content-container {
  max-width: 600px;
  margin: 0 auto;
}

.form-card {
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 25px;
}

.form-group label {
  display: block;
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.required {
  color: #f44336;
  margin-right: 4px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 15px;
  transition: all 0.3s;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-group select {
  cursor: pointer;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23333' d='M6 9L1 4h10z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 16px center;
  padding-right: 40px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 35px;
}

.btn {
  flex: 1;
  padding: 14px 30px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-primary {
  background: #4CAF50;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #45a049;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(76, 175, 80, 0.4);
}

.btn-primary:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.btn-secondary {
  background: white;
  color: #666;
  border: 2px solid #ddd;
}

.btn-secondary:hover {
  background: #f8f9fa;
  border-color: #999;
}

/* 结果弹窗 */
.result-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.result-content {
  background: white;
  border-radius: 16px;
  padding: 30px;
  max-width: 500px;
  width: 90%;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.result-header {
  text-align: center;
  margin-bottom: 20px;
}

.result-icon {
  font-size: 48px;
  display: block;
  margin-bottom: 15px;
}

.result-header h3 {
  font-size: 24px;
  color: #333;
}

.result-header.success h3 {
  color: #4CAF50;
}

.result-header.error h3 {
  color: #f44336;
}

.result-body {
  text-align: center;
  margin-bottom: 20px;
}

.result-body p {
  font-size: 16px;
  color: #666;
  margin-bottom: 15px;
}

.result-details {
  text-align: left;
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  max-height: 200px;
  overflow-y: auto;
}

.result-details pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-size: 13px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header h1 {
    font-size: 28px;
  }
  
  .form-card {
    padding: 25px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>

